<script lang="ts">
	import { goto } from '$app/navigation';
	import { page } from '$app/state';
	import type { ResourceInfo } from '$lib/api/proto/resource_api';
	import type { CardInfo } from '$lib/api/proto/resource_card_api';
	import { appStore } from '$lib/stores/app.svelte';
	import { userStore } from '$lib/stores/user.svelte';
	import { callApi } from '$lib/utils/call_utils';
	import { ChevronsLeft, Search } from 'lucide-svelte';
	import EditCardModal from './EditCardModal.svelte';
	import ResourceCard from './ResourceCard.svelte';

	const PAGE_SIZE = 12;

	const resourceId = page.url.searchParams.get('resourceId') ?? '';
	let resourceInfo: ResourceInfo | null = $state(null);

	let tmpKeyword = $state('');
	let keyword = $state('');

	let showCreateModal = $state(false);

	let cardList = $state([] as CardInfo[]);
	let totalCount = $state(0);
	let curPage = $state(0);

	const pageCount = $derived(Math.ceil((totalCount ?? 0) / PAGE_SIZE));

	async function loadResourceInfo() {
		if (userStore.userSession == null) {
			return;
		}
		const res = await callApi(
			appStore.resourceApiClient.get({
				sessionId: userStore.userSession,
				resourceId: resourceId
			}).response
		);
		if (res.resource != undefined) {
			resourceInfo = res.resource;
		}
	}

	async function loadCardList() {
		if (userStore.userSession == null) {
			return;
		}
		const res = await callApi(
			appStore.resourceCardApiClient.list({
				sessionId: userStore.userSession,
				resourceId: resourceId,
				withContent: true,
				filterByKeyword: keyword.trim() != '',
				keyword: keyword.trim(),
				offset: PAGE_SIZE * curPage,
				limit: PAGE_SIZE
			}).response
		);
		totalCount = res.totalCount;
		cardList = res.cardList;
	}

	async function onUpdateCard(cardId: string) {
		if (userStore.userSession == null) {
			return;
		}
		const res = await callApi(
			appStore.resourceCardApiClient.get({
				sessionId: userStore.userSession,
				resourceId: resourceId,
				cardId: cardId
			}).response
		);
		const tmpList = cardList.slice();
		const index = tmpList.findIndex((item) => item.cardId == cardId);
		if (index != -1 && res.card != undefined) {
			tmpList[index] = res.card;
			cardList = tmpList;
		}
	}

	$effect(() => {
		loadResourceInfo();
	});

	$effect(() => {
		loadCardList();
	});

	$effect(() => {
		if (tmpKeyword == '') {
			keyword = '';
		}
	});
</script>

<div class="ml-[100px] mr-[100px] mt-1">
	<div class="flex justify-between border-b-2 border-base-200 h-[50px]">
		<div class="flex gap-2">
			<button type="button" class="btn btn-ghost p-1" onclick={() => goto('/app')}>
				<ChevronsLeft size="32" />
			</button>
			<h3 class="text-3xl">知识卡片库:{resourceInfo?.basicInfo?.name}</h3>
		</div>
		<div class="flex items-center gap-4">
			<label class="input w-[180px]">
				<input
					type="search"
					class="input"
					placeholder="过滤标题"
					bind:value={tmpKeyword}
					onkeypress={(e) => {
						if (e.key === 'Enter') {
							keyword = tmpKeyword;
						} else if (e.key == 'Esc') {
							tmpKeyword = '';
						}
					}}
				/>
				<button type="button" class="btn btn-ghost p-1" onclick={() => (keyword = tmpKeyword)}
					><Search /></button
				>
			</label>
			<button class="btn btn-primary" onclick={() => (showCreateModal = true)}>创建</button>
		</div>
	</div>

	<div class="h-[calc(100vh-110px)] overflow-y-auto w-full p-2">
		<div class="flex flex-wrap gap-2">
			{#each cardList as card}
				<ResourceCard
					{resourceId}
					cardInfo={card}
					onChange={() => onUpdateCard(card.cardId)}
					onRemove={() => loadCardList()}
					onLink={() => loadCardList()}
				/>
			{/each}
		</div>
		{#if pageCount > 1}
			<div class="flex justify-center mt-[20px]">
				<div class="join bg-base-200">
					{#if curPage > 0}
						<button class="join-item btn btn-lg" onclick={() => (curPage = curPage - 1)}
							>上一页</button
						>
					{/if}
					{#if curPage != 0}
						<button
							class="join-item btn btn-lg {curPage == 0 ? 'btn-active' : ''}"
							onclick={() => (curPage = 0)}>1</button
						>
					{/if}
					{#if pageCount > 3 && curPage > 1}
						<button class="join-item btn btn-lg btn-disabled">...</button>
					{/if}
					{#if curPage < pageCount}
						<button class="join-item btn btn-lg btn-active">{curPage + 1}</button>
					{/if}
					{#if curPage + 1 < pageCount}
						<button class="join-item btn btn-lg" onclick={() => (curPage += 1)}
							>{curPage + 2}</button
						>
					{/if}
					{#if pageCount - curPage > 4}
						<button class="join-item btn btn-lg btn-disabled">...</button>
					{/if}
					{#if pageCount - curPage > 3}
						<button class="join-item btn btn-lg" onclick={() => (curPage = pageCount - 2)}
							>{pageCount - 1}</button
						>
					{/if}
					{#if pageCount - curPage > 2}
						<button class="join-item btn btn-lg" onclick={() => (curPage = pageCount - 1)}
							>{pageCount}</button
						>
					{/if}
					{#if curPage + 1 < pageCount}
						<button class="join-item btn btn-lg" onclick={() => (curPage = curPage + 1)}
							>下一页</button
						>
					{/if}
				</div>
			</div>
		{/if}
	</div>
</div>

<div class="absolute -left-[10000px]">
	{#if showCreateModal}
		<EditCardModal
			{resourceId}
			onCancel={() => (showCreateModal = false)}
			onOk={() => {
				showCreateModal = false;
				if (curPage == 0) {
					loadCardList();
				} else {
					curPage = 0;
				}
			}}
		/>
	{/if}
</div>
